const db = uniCloud.database();
// 引入云对象
const utilsObj = uniCloud.importObject('utilsObj', {
	// 移除自带loadding
	customUI: true
});
//获取富文本内的图片url地址
export function getImgSrc(richtext, num = 3) {
	let imgList = [];
	richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
		imgList.push(capture);
	});
	imgList = imgList.slice(0, num)
	return imgList;
}

//向外导出省份
export function getProvince() {
	return new Promise((resolve, reject) => {
		let historyProvince = uni.getStorageSync("historyProvince");
		// 定位信息不存在
		if (historyProvince) {
			// ip定位过期  时间超过一小时 （现在时间 - 过去时间）小于一小时更新
			if ((Date.now() - historyProvince.time) > 1000 * 60 * 60) {
				console.log("ip过期刷新了缓存");
				getIp().then(res => {
					resolve(res)
				}).catch(err => {
					reject(err)
				})
			} else {
				// 获取缓存
				console.log("获取了缓存", historyProvince);
				resolve(historyProvince);
			}
		} else {
			// 获取定位信息
			getIp().then(res => {
				console.log("没有记录获取定位");
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		}
	})
}

//获取所在省市
function getIp() {
	return new Promise((resolve, reject) => {
		uni.request({
			url: "https://restapi.amap.com/v3/ip?key=d30039ca71a2626d7f62c7524059acff",
			success: res => {
				console.log("获取定位api执行", res);
				let city = typeof(res.data.city) == "string" ? res.data.city : "";
				let province = typeof(res.data.province) == "string" ? res.data.province : "";
				let cityCode = typeof(res.data.adcode) == "string" ? res.data.adcode : ""
				let obj = {
					cityStr: `${province}/${city}`,
					cityCode,
					time: Date.now()
				}
				uni.setStorageSync("historyProvince", obj);
				resolve(obj)

			},
			fail: err => {
				reject(err)
			}
		})
	})
}
export function giveName(item) {

	return item.user_id[0] && (item.user_id[0].nickname || item.user_id[0].username || item.user_id[0].mobile ||
		"请设置昵称")
}
export function giveAvatar(item) {
	// 空值合并
	return item.user_id[0]?.avatar_file?.url ?? "'../../static/images/user-default.jpg'"
}
// 点赞方法
export async function likeFun(artId) {
	try {
		// 获取点赞表查询（当前文章 当前用户有没有点赞） 获取查询数量
		let count = await db.collection('quanzi_like').where(
			`article_id=="${artId}" && user_id==$cloudEnv_uid`).count();
		console.log(count.result.total, '统计点赞数量');
		// 没有则点赞
		if (!count.result.total) {
			let add = await db.collection('quanzi_like').add({
				article_id: artId
			});

			let res = await utilsObj.operation('quanzi_artcle', 'like_count', artId, 1);
			console.log('res自增添加点赞量', res);
			console.log(res, '添加');
			return;
		}
		// 点赞过
		let remove = await db.collection('quanzi_like').where(
			`article_id=="${artId}" && user_id==$cloudEnv_uid`).remove();
		let res = await utilsObj.operation('quanzi_artcle', 'like_count', artId, -1);
		console.log('res自减，减少点赞量', res);
		console.log(remove, '删除');
	} catch (e) {
		//TODO handle the exception
	}
}